package com.goods.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.goods.business.mapper.*;
import com.goods.business.service.IOutStockService;
import com.goods.common.error.SystemCodeEnum;
import com.goods.common.error.SystemException;
import com.goods.common.model.business.*;
import com.goods.common.utils.ListPageUtils;
import com.goods.common.vo.business.ConsumerVO;
import com.goods.common.vo.business.OutStockDetailVO;
import com.goods.common.vo.business.OutStockItemVO;
import com.goods.common.vo.business.OutStockVO;
import com.goods.common.vo.system.PageVO;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA
 *
 * @Date: 2023/3/6 - 15:27
 * @Author: Hyoung
 * @Description:
 */
@Service
public class OutStockServiceImpl implements IOutStockService {

    @Autowired
    private IOutStockMapper iOutStockMapper;

    @Autowired
    private IOutStockDetailMapper iOutStockDetailMapper;

    @Autowired
    private IConsumerMapper iConsumerMapper;

    @Autowired
    private IProductMapper iProductMapper;

    @Autowired
    private IProductStockMapper iProductStockMapper;

    @Autowired
    private IOutStockInfoMapper iOutStockInfoMapper;

    @Override
    public PageVO<OutStockVO> findOutStockList(Integer pageNum, Integer pageSize, OutStockVO outStockVO) {
        PageHelper.startPage(pageNum, pageSize);
        Example example = new Example(OutStock.class);
        Integer status = outStockVO.getStatus();
        Integer type = outStockVO.getType();
        String outNum = outStockVO.getOutNum();

        Example.Criteria criteria = example.createCriteria();
        if (!Objects.isNull(status)) {
            criteria.andEqualTo("status", status);
        }
        if (!Objects.isNull(type)) {
            criteria.andEqualTo("type", type);
        }
        if (!StringUtils.isEmpty(outNum)) {
            criteria.andLike("outNum", "%" + outNum + "%");
        }

        List<OutStock> outStocks = iOutStockMapper.selectByExample(example);
        List<OutStockVO> collect = outStocks.stream().map(outStock -> {
            OutStockVO outStockVOTemp = new OutStockVO();
            BeanUtils.copyProperties(outStock, outStockVOTemp);
            // 查询用户
            Long consumerId = outStock.getConsumerId();
            Consumer consumer = iConsumerMapper.selectByPrimaryKey(consumerId);
            outStockVOTemp.setName(consumer.getName());
            outStockVOTemp.setPhone(consumer.getPhone());
            return outStockVOTemp;
        }).collect(Collectors.toList());
        return new PageVO<>(collect.size(), collect);
    }

    @Override
    public void remove(Integer id) {
        OutStock outStock = new OutStock();
        outStock.setId(Long.valueOf(id));
        outStock.setStatus(1);
        iOutStockMapper.updateByPrimaryKeySelective(outStock);
    }

    @Override
    public void back(Integer id) {
        OutStock outStock = new OutStock();
        outStock.setId(Long.valueOf(id));
        outStock.setStatus(2);
        iOutStockMapper.updateByPrimaryKeySelective(outStock);
    }

    @Override
    public void delete(Integer id) {
        iOutStockMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void publish(Integer id) {
        OutStock outStock = new OutStock();
        outStock.setId(Long.valueOf(id));
        outStock.setStatus(0);
        iOutStockMapper.updateByPrimaryKeySelective(outStock);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @SneakyThrows
    public void addOutStock(OutStockVO outStockVO) {

        // 操作人
        // product减少数量
        //
        System.out.println(outStockVO);
        // 如果不为空就直接保存
        if (Objects.isNull(outStockVO.getConsumerId())) {
            // 否则就新增一个消费者
            Consumer consumer = new Consumer();
            consumer.setName(outStockVO.getName());
            consumer.setPhone(outStockVO.getPhone());
            consumer.setAddress(outStockVO.getAddress());
            consumer.setSort(outStockVO.getSort());
            consumer.setContact(outStockVO.getContact());
            consumer.setCreateTime(new Date());
            consumer.setModifiedTime(new Date());
            iConsumerMapper.insertSelective(consumer);
            // 主键回显
            outStockVO.setConsumerId(consumer.getId());
        }

//        OutStock outStock = new OutStock();
        // 生成一个订单号
        String outNum = UUID.randomUUID().toString().replace("-", "");
        outStockVO.setOutNum(outNum);
        outStockVO.setCreateTime(new Date());
        outStockVO.setStatus(2); // 默认状态等待


        // out_stock_info 添加数量
//        List<OutStockInfo> outStockInfoList = new ArrayList<OutStockInfo>();
        List<Object> products = outStockVO.getProducts();
        Integer productNumberSum = 0;
        for (Object product : products) {
            OutStockInfo outStockInfo = new OutStockInfo();
            outStockInfo.setCreateTime(new Date());
            outStockInfo.setModifiedTime(new Date());
            outStockInfo.setOutNum(outNum);
            HashMap<String, Integer> temp = (HashMap<String, Integer>) product;
            Integer productNumber = temp.get("productNumber");
            // 出库等于所有的综合
            productNumberSum += productNumber;

            Long id = Long.valueOf(temp.get("productId"));
            Product productInfo = iProductMapper.selectByPrimaryKey(id);
            String pNum = productInfo.getPNum();
            outStockInfo.setPNum(pNum);

            //  更新库存数量
            Example exampleProductStock = new Example(ProductStock.class);
            exampleProductStock.createCriteria().andEqualTo("pNum", pNum);
            ProductStock productStock = iProductStockMapper.selectOneByExample(exampleProductStock);
            if (productNumber > productStock.getStock()) {
                throw new SystemException(SystemCodeEnum.STOCK_EMPTY, "商品库存不足");
            }
            productStock.setStock(productStock.getStock() - productNumber);
            iProductStockMapper.updateByPrimaryKey(productStock);
            iProductMapper.updateByPrimaryKey(productInfo);

            outStockInfo.setProductNumber(productNumber);
            iOutStockInfoMapper.insert(outStockInfo);

        }
        outStockVO.setProductNumber(productNumberSum);
        // 减少库存
        OutStock outStock = new OutStock();
        BeanUtils.copyProperties(outStockVO, outStock);
        iOutStockMapper.insert(outStock);


    }

    @Override
    public OutStockDetailVO detail(Integer id, Integer pageNum) {
//        PageHelper
//        PageHelper.startPage(pageNum,new Integer());
        OutStock outStock = iOutStockMapper.selectByPrimaryKey(id);

        //
        OutStockDetailVO outStockDetailVO = new OutStockDetailVO();
        // 查寻出消费者
        Example exampleConsumer = new Example(Consumer.class);
        exampleConsumer.createCriteria().andEqualTo("id", outStock.getConsumerId());
        Consumer consumer = iConsumerMapper.selectOneByExample(exampleConsumer);
        ConsumerVO consumerVO = new ConsumerVO();
        BeanUtils.copyProperties(consumer, consumerVO);
        outStockDetailVO.setConsumerVO(consumerVO);

        // 查询outstockinfo
        Example exampleOutStockInfo = new Example(OutStockInfo.class);
        exampleOutStockInfo.createCriteria().andEqualTo("outNum", outStock.getOutNum());
        List<OutStockInfo> outStockInfoList = iOutStockInfoMapper.selectByExample(exampleOutStockInfo);

        ArrayList<OutStockItemVO> outStockItemVOS = new ArrayList<>();
        for (OutStockInfo outStockInfo : outStockInfoList) {

            OutStockItemVO outStockItemVO = new OutStockItemVO();

            String pNum = outStockInfo.getPNum();
            Example exampleProduct = new Example(Product.class);
            exampleProduct.createCriteria().andEqualTo("pNum", pNum);
            Product product = iProductMapper.selectOneByExample(exampleProduct);
            if (!Objects.isNull(product)) {
                BeanUtils.copyProperties(product, outStockItemVO);
            }

     /*       Example exampleStock = new Example(ProductStock.class);
            exampleStock.createCriteria().andEqualTo("pNum", pNum);
            ProductStock productStock = iProductStockMapper.selectOneByExample(exampleStock);*/
            Example exampleOutStockInfoNum = new Example(OutStockInfo.class);
            Example.Criteria criteria = exampleOutStockInfoNum.createCriteria();
            criteria.andEqualTo("pNum", pNum);
            criteria.andEqualTo("outNum", outStock.getOutNum());
            OutStockInfo outStockInfoTemp = iOutStockInfoMapper.selectOneByExample(exampleOutStockInfoNum);
            outStockItemVO.setCount(Math.toIntExact(outStockInfoTemp.getProductNumber()));

            outStockItemVOS.add(outStockItemVO);
        }

        // 查询出product List<OutStockItem>outStockItemVOS
        outStockDetailVO.setItemVOS(ListPageUtils.page(outStockItemVOS, 4, pageNum));
        outStockDetailVO.setTotal(outStockItemVOS.size());

        return outStockDetailVO;
    }
}
